/**
*
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>模块列表</el-breadcrumb-item>
    </el-breadcrumb>
    <NoPermission
      v-if="!authFilter(permissionObj, 'index')">
    </NoPermission>

    <div v-else>

      <!--模块树 -->
      <div class="relative mgt20">
        <el-form label-width="80px" :model="editForm" ref="editForm" :rules="rules">
          <el-form-item label="语言"  prop="language">
            <el-select
              size="small"
              v-model="editForm.language"
              placeholder="语言"
              clearable
              filterable
              @change="changeLanguage">
              <el-option v-for="type in languageList" :label="type.label" :value="type.value" :key="type.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模块"  prop="treeData"
                        v-if="showContent">
            <cusTree
              ref="cusTree"
              :treeData="editForm.treeData"
              @addHanlde="addHanlde"
              @editHandle="editHandle"
              @delHandle="delHandle">
            </cusTree>
            <!-- 暂无数据 -->
            <div class="flex-align mgl30"
                 v-if="showOrder">
              <no-data
                class="mgt40 mgb20"
                title="暂无模块数据"
                nullName="nodata.png">
              </no-data>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer"
           class="dialog-footer mgt20"
           v-if="authFilter(permissionObj, 'save')">
        <el-button size="small" type="primary" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>

    </div>

  </div>
</template>

<script>
import {mapGetters} from "vuex";
import cusTree from '@/components/cus-tree/cus-tree.vue'

// import reportMin from "@/views/tatisticalReport/tatisticalReport.js"
export default {
  // 注册组件
  components: {
    cusTree,
  },
  // mixins:[reportMin],
  data() {
    return {
      isShowTag: 'cusTree',
      editForm: {
        treeData:[],
        //新增语言
        language:'zh-CN',
      },
      // rules 表单验证
      rules: {
        treeData: [
          { required: true, message: '请输入模块列表', trigger: 'blur' }
        ],
        //新增语言
        language: [{ required: true, message: '请选择语言', trigger: 'change' }],
      },
      languageList:[],
      showContent: false,
      // 防重复点击
      allowRequest: true,
      showOrder: false,

    }
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    const vm = this
    //新增语言
    vm.languageListGet().then(()=>{
      vm.getData({},true)
    })
  },
  computed:{
    ...mapGetters(['userAuthList']),
    permissionObj(){
      if(this.userAuthList&&this.userAuthList.length>0){
        return this.authListFilter(this.userAuthList,'customManagement', 'modulelist')
      }
    }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 模块组件start
    // 添加确认的回调
    addHanlde(node){
      // 这里是后端传递过来的id
      node.id =  new Date().getSeconds()
      console.log(node);
      this.recQueryHandle(this.editForm.treeData,node,"add")
      this.$refs.cusTree.forceFlush();
    },
    // 编辑的回调
    editHandle(node){
      // .. 发送后端请求
      this.recQueryHandle(this.editForm.treeData,node,"edit")
      this.$refs.cusTree.forceFlush();
    },
    // 删除
    delHandle(node){
      this.recQueryHandle(this.editForm.treeData,node,"del")
      this.$refs.cusTree.forceFlush();
    },
    recQueryHandle (treeData, curNode, tag) {
      // 当前操作的节点
      treeData.forEach((item) => {
        if (tag == 'add' && item.id == curNode.pid) {
          console.log('item.child', item)
          if (!item.child) {
            item.child = []
            //this.$set(item, 'child', [])
          }
          curNode.edit = false
          item.child.push(curNode)
        }

        if (item.id === curNode.id) {
          if (tag == 'edit') {
            item.edit = false;
            item.title = curNode.title
          } else if (tag === 'del') {
            let index = treeData.findIndex((t) => t.id == curNode.id)
            treeData.splice(index, 1)
          }
        }

        if (item.child && item.child.length > 0) {
          this.recQueryHandle(item.child, curNode, tag)
        }
      })
    },
    // 模块组件end
    getData(parameter={},allowRequest=false) {
      const vm = this
      vm.loading = true
      parameter = {
        ...parameter,
        language: vm.editForm.language
      }
      if(allowRequest){
        if(vm.allowRequest == false) return
        vm.allowRequest = false
        vm.openFullScreen()
      }

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      vm.$store.dispatch('moduleList', parameter,"POST")
        .then(res => {
          vm.loading = false
          const { data:{list=[]},code, msg } = res
          if (code != 0) {
            vm.showMessageMin({
              message: msg,
              type: 'error',
            })
          } else {
            vm.editForm = {
              ...vm.editForm,
              treeData: list
            }
          }
        })
        .finally(() => {
          vm.showContent = true
          if(allowRequest){
            vm.allowRequest = true
            vm.closeFullScreen(vm.openFullScreen());
          }
          if(vm.editForm.treeData&&vm.editForm.treeData.length>0){
            vm.showOrder = false
          }else {
            vm.showOrder = true
          }
        })
    },
    // 树形扁平化
    flatten(arr) {
      let result = []
      for (let item of arr) {
        // item.edit = (item.edit == true ? 1 : 0)
        let res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据作为第一层级的填充
        delete res['child']
        result.push(res)
        if (item.child instanceof Array && item.child.length > 0) { // 如果当前child为数组并且长度大于0，才可进入flag()方法
          result = result.concat(this.flatten(item.child))
        }
      }
      return result
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      const vm = this;
      vm.$refs[editData].validate(valid => {
        if (valid) {
          vm.openFullScreen();
          const treeData = vm.flatten(vm.editForm.treeData);
          const param = {
            treeData: treeData,
            language: vm.editForm.language
          }
          let request = vm.apiUrl.moduleEdit(param,"POST")
          request.then(res => {
            vm.closeFullScreen(vm.openFullScreen());
            const { code,msg } = res;
            if (code != 0) {
              vm.showMessageMin({
                type: 'error',
                message: msg
              })
            } else {
              vm.showMessageMin({
                type: 'success',
                message: '模块列表保存成功！'
              })
              vm.getData({})
            }
          })
        } else {
          return false
        }
      })
    },
    //获取语言列表
    languageListGet(){
      let vm = this

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      vm.openFullScreen()
      vm.showContent = false
      return new Promise((resolve)=>{
        vm.$store.dispatch('languageListGet', {},"POST")
          .then(res => {
            const { code, data = [], msg } = res;
            if (code != 0) {
              vm.closeFullScreen(vm.openFullScreen());
              this.$message({
                type: 'error',
                message: msg
              })
            } else {
              if(data&&data.length>0){
                vm.languageList = data;
              }
            }
          })
          .finally(() => {
            resolve()
          })
      })
    },
    changeLanguage(e){
      const vm = this
      // console.log('changeLanguage',e)
      vm.showContent = false
      vm.editForm = {
        ...vm.editForm,
        treeData: []
      }
      vm.getData({},true)
    },

  }
}
</script>

<style lang="less" scoped>

</style>
